package com.tianqu.tms.www.car.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAjaxAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.entity.RentalContractInfo;
import com.tianqu.tms.entity.TransferAcceptedInfo;

/**
 * mufeiyu
 */
public class CarSerialInfoListAjaxAction extends TmsAjaxAction {
	private Logger logger = Logger.getLogger(CarSerialInfoListAjaxAction.class);

	@Override
	public void process(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response, UserContext uc) throws TmsException {

		logger.debug(this.getClass().getName() + "#execute.");

		String type = request.getParameter("type");
		String query = request.getParameter("query");
		List list = new ArrayList();
		Map map = null;

		RentalContractInfo rental = RentalContractInfo.getInstance();
		if (StringUtil.isNotBlank(type) && !"1".equals(type)) {
			List<RentalContractInfo> rentalContractInfoList = new ArrayList<RentalContractInfo>();
			rentalContractInfoList = rental.findCarProxySerialList(query);
			for (RentalContractInfo rentalContractInfo : rentalContractInfoList) {
				map = new HashMap();
				map.put("value", rentalContractInfo.getSerial());
				map.put("data", rentalContractInfo.getId());
				list.add(map);
			}
		} else if ("1".equals(type)) {
			TransferAcceptedInfo acceptedInfo = TransferAcceptedInfo.getInstance();
			list.addAll(acceptedInfo.findSerialList(query,1));
		} else {
			List<RentalContractInfo> rentalContractInfoList = new ArrayList<RentalContractInfo>();
			rentalContractInfoList = rental.findContractSerialList(query);
			for (RentalContractInfo rentalContractInfo : rentalContractInfoList) {
				map = new HashMap();
				map.put("value", rentalContractInfo.getSerial());
				map.put("data", rentalContractInfo.getId());
				list.add(map);
			}
		}

		JSONArray jsonArray = JSONArray.fromObject(JSONArray.fromObject(list));
		JSONObject json = new JSONObject();
		json.put("query", query);
		json.put("suggestions", jsonArray);
		responseValues(response, json.toString(), TEXT);
		logger.debug(this.getClass().getName() + "#doAction was completed.");
	}
}
